﻿/**********************************************************************************************
           Project             - mLearning2
           Company             - IronOne Technologies
           Original Developer  - Dinusha Kumarasiri 
           EMail               - dinushak@IronOneTech.com
           Date                - 2010-December
           Note                - helper class to store authentication cookie
---------------------------------------------------------------------------------------------*/

using System;
using System.Web;
using System.Web.Security;

namespace BoardPACDAO.Auth
{
    public class LoginHandler : IHttpModule
    {
        public LoginHandler()
        {

        }

        private void OnPostAuthenticate(Object sender, EventArgs e)
        {
            Guid sessionToken;
            //UserDAO userDao = new UserDAO();
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContext httpContext = httpApplication.Context;
            if (httpContext.Request.FilePath != null && httpContext.Request.FilePath.Contains("Error.htm"))
            {
                return;
            }
            if (httpContext.User.Identity.IsAuthenticated)
            {
                FormsAuthenticationTicket authenticationTicket =
                    ((FormsIdentity)httpContext.User.Identity).Ticket;

                if (authenticationTicket.UserData != "")
                {
                    sessionToken = new Guid(authenticationTicket.UserData);
                }
                else
                {

                    FormsAuthentication.SignOut();
                    FormsAuthentication.RedirectToLoginPage();
                    return;
                }

                MembershipUser currentUser = Membership.GetUser(authenticationTicket.Name);

                Guid storedToken = new Guid(currentUser.Comment);

                if (sessionToken != storedToken)
                {
                    FormsAuthentication.SignOut();
                    FormsAuthentication.RedirectToLoginPage();
                }
            }
        }

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            string x = context.ToString();

            if (true)
            {
                context.PostAuthenticateRequest += new EventHandler(OnPostAuthenticate);
            }
        }
    }
}